package person.twj.securitysessionredis.core.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import person.twj.securitysessionredis.domain.po.SysUser;
import person.twj.securitysessionredis.service.ISysUserService;

import java.util.ArrayList;
import java.util.Collection;


/**
 * 校验前，从数据库中获取用户信息，包含密码
 */


public class MyUserDetailsService implements UserDetailsService {
    @Autowired
    private ISysUserService iSysUserService;


    // @TODO security:loadUserByUsername 1. 校验前，从数据库中获取用户信息，包含密码
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        SysUser user = iSysUserService.selectByUserName(username);
        if (user == null) {
            throw new BadCredentialsException("用户名或密码错误");
        } else {
            Collection<GrantedAuthority> authorities = new ArrayList<>();

            return User.builder()
                    .username(user.getUsername())
                    .password(user.getPassword())
                    .authorities(authorities)
                    .build();


        }

    }
}
